import random

from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha
from django import http

from celery_tasks.sms.tasks import send_sms_code
from libs.yuntongxun.sms import CCP
from utils.response_code import RETCODE

class ImageView(View):
    def get(self,request,uuid):
        name,code,image = captcha.generate_captcha()

        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s'%uuid,120,code)
        return http.HttpResponse(image,content_type='image/jpeg')
class SMSCodeView(View):
    def get(self,request,sms_codes):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code,uuid]):
            return http.JsonResponse({'code':RETCODE.NECESSARYPARAMERR,'errmsg':'缺少必传参数'})
        try:
            conn = get_redis_connection('code')
            redis_code = conn.get('img_%s'%uuid)
            if redis_code is None:
                return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'图形验证码失效'})
            if redis_code.decode().lower() != image_code.lower():
                return http.JsonResponse({'code':RETCODE.IMAGECODEERR,'errmsg':'验证码错误'})


        except:
            return http.HttpResponseBadRequest('redis链接错误')
        code = '%06d' % random.randint(0, 999999)
        send_flag = conn.get('codes_%s' % sms_codes)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        conn.setex('codes_%s' % sms_codes, 300, code)
        # CCP().send_template_sms(sms_codes, [code, 5], 1)
        send_sms_code.delay(sms_codes,code)
        return http.JsonResponse({'code':RETCODE.OK})

